package logic

import (
	"context"
	"fmt"
	"zhihu/models"

	"zhihu/zhihu_rpc/internal/svc"
	"zhihu/zhihu_rpc/zhihu_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
	return &UpdateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateUserLogic) UpdateUser(in *zhihu_rpc.UpdateUserRequest) (*zhihu_rpc.UpdateUserResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if models.DB.Where("id = ?", in.Id).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在")
	}
	user = models.User{
		UserName:      in.UserName,
		UserAccount:   in.UserAccount,
		UserPassword:  in.UserPassword,
		UserPhone:     in.UserPhone,
		UserHandImage: in.UserHandImage,
	}
	if models.DB.Model(&models.User{}).Where("id = ?", in.Id).Updates(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	log := models.UserLog{
		UserId: int(user.ID),
		Des:    "update his account data",
	}
	if models.DB.Create(&log).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &zhihu_rpc.UpdateUserResponse{}, nil
}
